package cn.hejiang.org.controller;


import cn.hejiang.basic.util.AjaxResult;
import cn.hejiang.basic.util.PageList;
import cn.hejiang.org.domain.Department;
import cn.hejiang.org.query.DepartmentQuery;
import cn.hejiang.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口", description = "部门接口详细描述")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    // 新增部门或修改部门
    @PutMapping
    @ApiOperation(value = "部门添加或修改", notes = "带Id为添加，没有就是新增")
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        try {
            // 判断id是为空
            if (department.getId() == null) {
                departmentService.add(department); // 如果id为空则调用add方法
            } else {
                departmentService.update(department);// 如果id不为空则调用update方法
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作异常，以滚出"); // 操作失败
        }

    }

    // 删除部门
    /**
     * 接口三要素：
     * 1.接口的请求地址：http://localhost:8080/dept/1
     * 2.接口的参数：@PathVariable("id") Long id
     * 3.接口的返回值：AjaxResult
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable Long id) {
        try {
            departmentService.delete(id); // 调用删除方法
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作异常，以滚出"); // 操作失败
        }
    }

    // 查询一个部门
    @GetMapping("/{id}")
    public Department queryById(@PathVariable Long id) {
        return departmentService.queryById(id);
    }

    // 查询所有部门
    @GetMapping
    public List<Department> queryAll() {
        return departmentService.queryAll();
    }

    // 分页 + 高级查询
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query) {
        return departmentService.queryPage(query);
    }

    /**
     * 批量删除
     * 前端传的为数组，用数组接收
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
            departmentService.patchDelete(ids); // 调用删除方法
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("操作异常，以滚出"); // 操作失败
        }
    }

    // 获取所有部门
    @GetMapping("/tree")
    public List<Department> queryTree() {
        return departmentService.queryTree();
    }

}
